<?php

require_once 'google/Google.php';
require_once 'google/GoogleDetails.php';
require_once 'google/GoogleOpenID.php';

class GoogleSocialPlugin extends SJB_SocialPlugin
{
	private $_profileFields = array();

	/**
	 * @var string
	 */
	protected static $network = 'google';

	protected static $aUserFields = array();

	/**
	 * @var null|Google
	 */
	private static $object = null;

	/**
	 * @return string
	 */
	public static function getNetwork()
	{
		return self::$network;
	}

	/**
	 * @return GoogleSocialPlugin
	 */
	public function init()
	{
		$this->cleanSessionData(self::$network);

		if (is_null(self::$object) && empty($_SESSION['sn']['authorized'])) {
			try {
				if (!isset($_GET['social_id'])) {
					$callback_url = SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI() . '?network=' . self::$network;

					self::$object = new Google($callback_url);


					if (empty($_REQUEST['openid_mode'])) {
						self::$object->_getRequestToken();
					}
					elseif ($_REQUEST['openid_mode'] === 'id_res') {
						self::$object = new Google();
						self::$oProfile = self::$object->getProfileInfo();
						
						if (self::$oProfile) {
							$this->flagSocialPluginInSession(self::$network);
							$this->getProfileInformation();

							// save new accessToken, profileInfo to DB
							self::saveProfileSystemInfo();

							/*
							 * if user already registered we should link his profile 
							 * with google id
							 */
							if ($oCurrentUser = SJB_UserManager::getCurrentUser()) {
								$this->setUserSocialIDByUserSID($oCurrentUser->getSID(), self::$oProfile->id);
								SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/my-account/');
							}
							elseif (!parent::ifUserIsRegistered(self::$network, null)) {
								// redirect user to registration page if he is not registered
								$this->redirectToRegistrationSocialPage();
							}
						}
						else {
							if (SJB_HelperFunctions::debugModeIsTurnedOn()) {
								SJB_HelperFunctions::debugInfoPush(self::$object, 'SOCIAL_PLUGINS');
							}
						}
					}
					else {
						// usually it is cancel mode
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL'));
					}
				}
			}
			catch (Exception $e) {
				echo $e->getMessage();
			}
		}
		elseif (self::$oProfile && !parent::ifUserIsRegistered(self::$network, null)) {
			/**
			 * if user already logged in using social plugin but not registered
			 * redirect him to registration social page
			 */
			$this->redirectToRegistrationSocialPage();
		}

		return $this;
	}

	/**
	 * @param string $profileSocialID
	 * @return bool|null
	 */
	public function initializeByProfileSocialID($profileSocialID)
	{
		if (!parent::ifUserIsRegistered(self::$network, $profileSocialID)) {
			return false;
		}

		if ($accessToken = $this->getProfileSavedAccessToken($profileSocialID)) {
			return $this->initialize($accessToken);
		}

		return false;
	}

	/**
	 * @param string $socialID
	 * @return mixed|null
	 */
	public function getProfileSavedAccessToken($socialID)
	{
		$socInfo = SJB_DB::query('SELECT `access` FROM `google` WHERE `google_id` = ?s', $socialID);

		if (!empty($socInfo)) {
			$socInfo = array_shift($socInfo);

			if (!empty($socInfo['access'])) {
				return unserialize($socInfo['access']);
			}
		}
		return null;
	}

	/**
	 *
	 * @param array|object $access_token
	 */
	public function initialize($access_token = null)
	{
		self::$object = new google();

		return $this->getProfileInformation();
	}

	public function __construct()
	{
		$_SESSION['sn']['authorized'] = (isset($_SESSION['sn']['authorized'])) ? $_SESSION['sn']['authorized'] : FALSE;

		if ($_SESSION['sn']['authorized'] === TRUE && self::$network === $_SESSION['sn']['network'] && !empty($_SESSION['google']['profile_info'])) {
			$this->initialize();
		}
	}

	/**
	 * @param string $referenceUID
	 * @return string
	 */
	public function getSocialIDByReferenceUID($referenceUID)
	{
		return substr($referenceUID, (strlen(self::$network) + 1));
	}

	/**
	 * save social information
	 * access token,
	 */
	public function saveProfileSystemInfo()
	{
		if ($oProfile = self::getProfileObject()) {
			$googleID = (string) $oProfile->id;
			$profileInfo = serialize($oProfile);

			if ($googleID && $profileInfo) {
				return SJB_DB::query('INSERT INTO `google` SET `google_id` = ?s, `profile_info` = ?s
					ON DUPLICATE KEY UPDATE `profile_info`=?s', $googleID, $profileInfo, $profileInfo);
			}

			return false;
		}

		return null;
	}

	/**
	 * @return bool|null
	 */
	private function getProfileInformation()
	{
		if (self::$object) {
			self::$oProfile = self::$object->getProfileInfo($this->_profileFields);

			if (self::$oProfile) {
				self::$oSocialPlugin = $this;

				if (!empty(self::$oProfile->email) && !SJB_UserManager::getUserSIDbyEmail(self::$oProfile->email)) {
					$key = array_search('email', self::$aUserFields);

					if ($key !== false) {
						unset(self::$aUserFields[$key]);
					}
				}

				if (SJB_Request::getVar('debug')) {
					echo '<h5>VARDUMP :: ' . __FILE__ . '::LINE ' . __LINE__ . '</h5><pre>';
					var_dump(self::$oProfile);
					echo '</pre>';
				}
				return true;
			}
			else {
				// revocation successful, clear session
				unset($_SESSION['google']);
			}
		}

		return null;
	}

	public static function logout()
	{
		if (self::$object && self::$oProfile) {
			unset($_SESSION['google']);
			unset($_SESSION['sn']);

			if (empty($_SESSION['google'])) {
				// session destroyed
			}
			else {
				// session not destroyed
				echo "Error clearing user's session";
			}
		}
	}

	/**
	 * @param SJB_Object $object
	 * @return SJB_Object
	 */
	public static function fillRegistrationDataWithUser(SJB_Object $object)
	{
		if (self::$oSocialPlugin instanceof GoogleSocialPlugin && $oProfile = self::getProfileObject()) {
			/** @var $oProperty SJB_ObjectProperty */
			foreach ($object->getProperties() as $oProperty) {
				$value = '';
				switch ($oProperty->getID()) {
					case 'Location':
						$value = true;
						break;

					case 'email':
						if (!empty($oProfile->email) && empty($_POST['email']))
							$value = array('original' => $oProfile->email, 'confirmed' => $oProfile->email);
						break;

					case 'FirstName':
						if (!empty($oProfile->firstName))
							$value = $oProfile->firstName;
						break;

					case 'LastName':
						if (!empty($oProfile->lastName))
							$value = $oProfile->lastName;
						break;

					case 'ContactName':
						if (!empty($oProfile->lastName))
							$value = $oProfile->firstName . ' ' . $oProfile->lastName;
						break;

					case 'WebSite':
						if (!empty($oProfile->website))
							$value = $oProfile->website;
						break;

					case 'sendmail':
						$value = false;
						break;

					case 'username':
					case 'password':
						continue(2);
						break;

					default:
						$propertyCanBeDeleted = !in_array($oProperty->getID(), self::$aUserFields)
								&& !in_array($oProperty->getID(), self::$aListingFields)
								&& !$oProperty->isRequired();
						if ($propertyCanBeDeleted) {
							$object->deleteProperty($oProperty->getID());
						}
						break;
				}
				if (!empty($value)) {
					$reqVal = SJB_Request::getVar($oProperty->getID(), false);
					if (empty($reqVal)) 	// if user did not modified his data in form
						$object->setPropertyValue($oProperty->getID(), $value);
				}
			}
		}

		return $object;
	}

	/**
	 * @return array
	 */
	function pluginSettings()
	{
		return SJB_GoogleDetails::getDetails(array());
	}


}



